package com.tuantuan.utils;

import java.net.HttpURLConnection;
import java.net.URLEncoder;

import com.google.gson.Gson;
import com.tuantuan.model.ReturnMesg;

/**
 * 
 * 获取用户的token
 * GetTokenUtils<BR>
 * 时间：2016年2月28日-下午12:42:21 <BR>
 * @version 1.0.0
 *
 */
public class GetTokenUtils {

	
	private static  String appKey="25wehl3uwoz6w";
	private static  String appSecret="V4HG6QexMHx";
	private static  String RONGCLOUDURI = "http://api.cn.ronghub.com";
	public static  String GETTOKENURL = "/user/getToken.";
	public static  String REFRESH = "/user/refresh.";
	
	private static final String UTF8 = "UTF-8";
	/**
	 * 
	 * 
	 * 方法名：getToken<BR>
	 * 时间：2016年2月28日-下午12:30:54 <BR>
	 * @param username 用户名
	 * @param porttraitUri 用户头像uri
	 * @return String<BR>
	 * TODO
	 */
	public static String getToken(String userId,String portraitUri,String url){
		String token="";
		try {
			SdkHttpResult tokenResult = getToken(appKey, appSecret, userId, userId, portraitUri, FormatType.json,url);
			String json=tokenResult.getResult();
			Gson gson=new Gson();
			ReturnMesg fromJson = gson.fromJson(json, ReturnMesg.class);
			token=fromJson.getToken();
		} catch (Exception e) {
			
			e.printStackTrace();
		}
		return token;
	}
	
	public static SdkHttpResult getToken(String appKey, String appSecret,
			String userId, String userName, String portraitUri,
			FormatType format,String url) throws Exception {

		HttpURLConnection conn = HttpUtil
				.CreatePostHttpConnection(appKey, appSecret, RONGCLOUDURI
						+ url + format.toString());

		StringBuilder sb = new StringBuilder();
		sb.append("userId=").append(URLEncoder.encode(userId, UTF8));
		sb.append("&name=").append(URLEncoder.encode(userName==null?"":userName, UTF8));
		sb.append("&portraitUri=").append(URLEncoder.encode(portraitUri==null?"":portraitUri, UTF8));
		HttpUtil.setBodyParameter(sb, conn);

		return HttpUtil.returnResult(conn);
	}
}
